package com.zb.nio.selector;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

import org.junit.Test;

/**
 * @author: zhaobin
 * @date: 2024/1/28 17:22
 * @Description:
 */
public class SelectorDemo2 {

    public static void main(String[] args) throws Exception{
        // 1、获取通道，绑定主机和端口号
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

        // 2、切换到非阻塞模式
        socketChannel.configureBlocking(false);

        // 3、创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 自定义输入
        Scanner scanner = new Scanner(System.in);
        java.lang.String d = "";
        System.out.println("请输入发送内容...");
        while (scanner.hasNext()) {
            // 5、向缓冲区写入数据
            d = "[" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss")) + "] " + scanner.nextLine();
            byteBuffer.put(d.getBytes());
            // 6、缓冲区读写模式切换
            byteBuffer.flip();
            // 7、把数据从缓冲区写入通道
            socketChannel.write(byteBuffer);

            // 清空缓冲区
            byteBuffer.clear();
        }
    }

    /**
     * 服务端代码
     * @throws Exception
     */
    @Test
    public void ServerDemo() throws Exception {
        // 1、获取服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 2、切换非阻塞模式
        serverSocketChannel.configureBlocking(false);

        // 3、绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(8080));

        // 4、获取selector选择器
        Selector selector = Selector.open();

        // 5、通道注册到选择器，进行监听
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 6、选择器进行轮询，后续操作
        while (selector.select() > 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()) {
                // 获取就绪操作
                SelectionKey selectionKey = selectionKeyIterator.next();
                // 判断什么操作
                if (selectionKey.isAcceptable()) {
                    // 获取连接
                    SocketChannel accept = serverSocketChannel.accept();
                    // 切换非阻塞模式
                    accept.configureBlocking(false);
                    // 注册
                    accept.register(selector, SelectionKey.OP_READ);
                } else if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel)selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

                    // 读取数据
                    int length = 0;
                    while ((length = channel.read(byteBuffer)) > 0) {
                        byteBuffer.flip();
                        System.out.println(new java.lang.String(byteBuffer.array(), 0, length));
                        byteBuffer.clear();
                    }
                }
            }
            selectionKeyIterator.remove();
        }
    }


}
